package com.fz.study.project.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.fz.study.project.entity.Result;
import com.fz.study.project.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        获取url信息
        String url = request.getRequestURL().toString();
        log.info("获取到的url数据为:{}",url);
//        判断url中是否包含登录信息
        if (url.contains("login") || url.contains("swagger") || url.contains("docs")){
//            包含就放行
            return true;
        }
//        获取登陆信息的jwt信息
        String jwt = request.getHeader("token");
//        判断jwt是否为空
        if (!StringUtils.hasLength(jwt)){
            Result notLogin = Result.error("NOT_LOGIN");
//            将对象转变成json数据传递给前端
            String error = JSONObject.toJSONString(notLogin);
//            响应给前端
            response.getWriter().write(error);
            return false;
        }
//        校验jwt数据的有效性
        try {
            JwtUtils.parseJwt(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            Result notLogin = Result.error("令牌有效性异常！");
//            将对象转变成json数据传递给前端
            String error = JSONObject.toJSONString(notLogin);
//            响应给前端
            response.getWriter().write(error);
            return false;
        }
//        放行
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
